package com.health_and_exercise.healthandexercisev1.app;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.CountDownTimer;
import android.os.Vibrator;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Random;


public class MainActivity extends ActionBarActivity {
    private static final float MAX_VALUE = (float) Math.pow(2.0, 20);

    private long targetTimeMilli;
    private long remainingTimeSeconds;
    private int numOfSteps;
    private int numOfJumps;
    private int targetSteps;
    private float lightReading;
    private float proximityReading;
    private TextView stepCounterTextView;
    private TextView lightReadingTextView;
    private TextView proximityReadingTextView;
    private TextView stepDetectionCountTextView;
    private TextView countDownTimerTextView;
    private TextView jumpCounterTextView;
    private boolean accomplished = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        lightReadingTextView = (TextView) findViewById(R.id.lightReadingTextView);
        proximityReadingTextView = (TextView) findViewById(R.id.proximityReadingTextView);
        stepDetectionCountTextView = (TextView) findViewById(R.id.stepDetectionCountTextView);
        countDownTimerTextView = (TextView) findViewById(R.id.countDownTimerTextView);
        jumpCounterTextView = (TextView) findViewById(R.id.jumpCountTextView);

        if (savedInstanceState!= null && savedInstanceState.containsKey("STEP_COUNTER")) {
            numOfSteps = savedInstanceState.getInt("STEP_COUNTER");
            stepDetectionCountTextView.setText("Step Counter by Detection: "
                + String.valueOf(numOfSteps));
        } else {
            numOfSteps = 0;
        }

        if (savedInstanceState!= null && savedInstanceState.containsKey("LIGHT_READING")) {
            lightReading = savedInstanceState.getFloat("LIGHT_READING");
            lightReadingTextView.setText("Light Reading: "
                    + String.valueOf(lightReading));
        } else {
            lightReading = MAX_VALUE;
        }

        if (savedInstanceState!= null && savedInstanceState.containsKey("PROXIMITY_READING")) {
            proximityReading = savedInstanceState.getFloat("PROXIMITY_READING");
            proximityReadingTextView.setText("Proximity Reading: "
                    + String.valueOf(proximityReading));
        } else {
            proximityReading = MAX_VALUE;
        }

        if (savedInstanceState != null && savedInstanceState.containsKey("TARGET_TIME")) {
            targetTimeMilli = savedInstanceState.getLong("TARGET_TIME");
        } else {
            targetTimeMilli = getIntent().getLongExtra("TARGET_TIME", System.currentTimeMillis());
        }

        if (savedInstanceState != null && savedInstanceState.containsKey("JUMP_COUNTER")) {
            numOfJumps = savedInstanceState.getInt("JUMP_COUNTER");
        } else {
            numOfJumps = 0;
        }

        if (savedInstanceState != null && savedInstanceState.containsKey("ACCOMPLISHED")) {
            accomplished = savedInstanceState.getBoolean("ACCOMPLISHED");
        } else {
            accomplished = false;
        }

        if (savedInstanceState != null && savedInstanceState.containsKey("TARGET_STEP")) {
            targetSteps = savedInstanceState.getInt("TARGET_STEP");
        } else {
            targetSteps = getIntent().getIntExtra("TARGET_STEP", 0);
        }

        Intent toBackgroundService = new Intent(this, BackgroundService.class);
        Bundle mainActivityToServiceExtras = new Bundle();
        mainActivityToServiceExtras.putLong("TARGET_TIME", targetTimeMilli);
        Log.d("MainActivity", "targetSteps = " + String.valueOf(targetSteps));
        mainActivityToServiceExtras.putInt("TARGET_STEP", targetSteps);
        toBackgroundService.putExtras(mainActivityToServiceExtras);
        startService(toBackgroundService);

        IntentFilter filter = new IntentFilter("BROADCAST_ACTION");
        ResponseReceiver responseReceiver = new ResponseReceiver();
        registerReceiver(responseReceiver, filter);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("STEP_COUNTER", numOfSteps);
        outState.putInt("JUMP_COUNTER", numOfJumps);
        outState.putFloat("LIGHT_READING", lightReading);
        outState.putFloat("PROXIMITY_READING", proximityReading);
        outState.putLong("TARGET_TIME", targetTimeMilli);
        outState.putLong("REMAINING_SECONDS", remainingTimeSeconds);
        outState.putInt("TARGET_STEP", targetSteps);
        outState.putBoolean("ACCOMPLISHED", accomplished);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    // Broadcast receiver for receiving status updates from the IntentService
    private class ResponseReceiver extends BroadcastReceiver
    {
        @Override
        public void onReceive(Context context, Intent intent) {


            Bundle extras = intent.getExtras();
            //Log.d("BROADCAST_BUNDLE: ", "bundle.lightReading = " + extras.containsKey("LIGHT_READING"));
            if (extras != null) {
                remainingTimeSeconds = extras.getLong("REMAINING_SECONDS");
                countDownTimerTextView.setText("Count Down Timer: " +
                        String.valueOf(remainingTimeSeconds));

                lightReading = extras.getFloat("LIGHT_READING");
                lightReadingTextView.setText("Light Reading: " + String.valueOf(lightReading));

                proximityReading = extras.getFloat("PROXIMITY_READING");
                proximityReadingTextView.setText("Proximity Reading: "
                        + String.valueOf(proximityReading));

                numOfSteps = extras.getInt("NUM_OF_STEPS");
                stepDetectionCountTextView.setText("Step Counter by Detection: "
                        + String.valueOf(numOfSteps));

                numOfJumps = extras.getInt("NUM_OF_JUMPS");
                jumpCounterTextView.setText("Jump Counter: " + String.valueOf(numOfJumps));

                boolean isLGTM = extras.getBoolean("LGTM");
                if (isLGTM) {
                    accomplished = isLGTM;
                    countDownTimerTextView.setText("Congratulations! You did it!");
                } else {
                    if (remainingTimeSeconds == 0 && !accomplished) {
                        countDownTimerTextView.setText("Oh no! You can do better!");
                    }
                }

                //Log.d("MainActivity: ", "lightReading = " + String.valueOf(lightReading) +
                //        "; proximityReading = " + String.valueOf(proximityReading) +
                //        "; remaining_seconds = " + String.valueOf(remainingTimeSeconds));

            } else {
                countDownTimerTextView.setText("WTF");
            }
        }

    }
}
